package com.v1.video.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;

/**
 * 图片简单处理工具类
 * 
 * @author wanfang
 * 
 */
public class ImageUtils {

	/**
	 * 根据文件Uri获取路径
	 * 
	 * @param context
	 * @param uri
	 * @return
	 */
	public static String getFilePathByFileUri(Context context, Uri uri) {
		String filePath = null;
		final String scheme = uri.getScheme();
		if (scheme == null)
			filePath = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			filePath = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						filePath = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return filePath;
	}

	/**
	 * 根据图片原始路径获取图片缩略图
	 * 
	 * @param imagePath
	 *            图片原始路径
	 * @param width
	 *            缩略图宽度
	 * @param height
	 *            缩略图高度
	 * @return
	 */
	public static Bitmap getImageThumbnail(String imagePath, int width,
			int height) {
		Bitmap bitmap = null;
		if (!TextUtils.isEmpty(imagePath)) {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;// 不加载直接获取Bitmap宽高
			// 获取这个图片的宽和高，注意此处的bitmap为null
			bitmap = BitmapFactory.decodeFile(imagePath, options);
			if (bitmap == null) {
				// 计算缩放比
				int h = options.outHeight;
				int w = options.outWidth;
				int beWidth = w / width;
				int beHeight = h / height;
				int rate = 1;
				if (beWidth < beHeight) {
					rate = beWidth;
				} else {
					rate = beHeight;
				}
				if (rate <= 0) {// 图片实际大小小于缩略图,不缩放
					rate = 1;
				}
				options.inSampleSize = rate;
				options.inJustDecodeBounds = false;
				// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
				bitmap = BitmapFactory.decodeFile(imagePath, options);
				// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
				bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
						ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
			}
		}
		return bitmap;
	}

}
